﻿namespace Blaze.ConfigExporters
{
    using System.Collections.Generic;
    using System.Linq;
    using Aspose.Cells;
    using ConfigExportTool;
    using ConfigExportTool.Readers;
    using Configs;

    /// <summary>
    /// 红点配置导出。
    /// </summary>
    public class NotificationExporter : ExporterBase
    {
        /// <summary>
        /// 导出客户端配置。
        /// </summary>
        protected override void ExportForClient()
        {
            ExportToClient(mDb, "NotificationConfig");
        }

        /// <summary>
        /// 初始化。
        /// </summary>
        protected override void Initialize()
        {
            var workbook = GetWorkbook("红点配置表.xlsx");
            readNodes(workbook);
            mDb = new NotificationDB
            {
                Nodes = mNodes.Where(n => !n.IsDevelopment || IsDevelopment).ToArray()
            };
        }

        private void readNodes(Workbook workbook)
        {
            var worksheet = workbook.Worksheets["节点配置"];
            var reader = new ByOffsetReader(worksheet.Cells[1, 0]).AsByRow();
            while (!reader.IsEmpty)
            {
                var lineReader = new ByOffsetReader(reader.Current).AsByColumn();
                var node = new NotificationDB.NodeConfig
                {
                    Id = lineReader.ReadInt32(),
                    Parent = lineReader.ReadInt32(0),
                    DisplayCount = lineReader.ReadBoolean(),
                    IsDevelopment = lineReader.ReadBoolean(),
                    LogicClass = lineReader.ReadNullableString()
                };
                mNodes.Add(node);
                reader.Skip();
            }

            //组装子节点列表
            foreach (var node in mNodes)
            {
                var children = mNodes.Where(n => n.Parent == node.Id).Select(n => n.Id).ToArray();
                if (children.Length > 0)
                    node.Children = children;
            }
        }

        private NotificationDB mDb;
        private readonly List<NotificationDB.NodeConfig> mNodes = new List<NotificationDB.NodeConfig>();
    }
}